package alibaba.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
@RequestMapping("consumer/circle")
@Slf4j
public class CircleBreakerController {

    public static final String SERVER_URL = "http://nacos-payment-provider";

    @Resource
    private RestTemplate restTemplate;

    @RequestMapping("fallback/{id}")
    // @SentinelResource(value = "fallback") // 什么都没有配置
    //@SentinelResource(value = "fallback",fallback = "handlerFallback") // fallback只负责业务异常
    //@SentinelResource(value = "fallback",blockHandler = "blockHandler") // blockHandler只负责sentinel控制台配置违规
    @SentinelResource(value = "fallback",fallback = "handlerFallback",blockHandler = "blockHandler",  // 既要管业务异常，还要管sentinel控制台配置违规
    exceptionsToIgnore = {IllegalArgumentException.class}) // 该异常不会被拦截
    public CommonResult<Payment> fallback (@PathVariable("id") Long id){
        CommonResult<Payment> commonResult = restTemplate.getForObject(SERVER_URL+"/payment/paymentSQL/"+id,CommonResult.class,id);
        if ( id == 4 ) {
            throw new IllegalArgumentException("IllegalArgumentException非法参数异常");
        } else if (commonResult.getData() == null ) {
            throw new NullPointerException("NullPointerException,该id没有对应记录，空指针异常");
        }
        return commonResult;
    }

    public CommonResult handlerFallback(@PathVariable("id") Long id,Throwable e) {
        Payment payment = new Payment(id,null);
        return new CommonResult<>(4444,"兜底异常handlerFallback，excepthion内容"+e.getMessage(),payment);
    }

    public CommonResult blockHandler(@PathVariable("id") Long id, BlockException blockException) {
        Payment payment = new Payment(id,null);
        return new CommonResult<>(4455,"blockHandler-sentinel限流，无此流水：BlockExcepthion"+blockException.getMessage(),payment);
    }
}
